package com.leyou.user.service;

import com.leyou.common.enums.LyExceptionEnum;
import com.leyou.common.exceptions.LyException;
import com.leyou.common.utils.BeanHelper;
import com.leyou.user.dto.UserDTO;
import com.leyou.user.mapper.UserMapper;
import com.leyou.user.pojo.User;
import jdk.nashorn.internal.ir.BreakableNode;
import org.apache.el.parser.BooleanNode;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import javax.validation.Valid;

@Service
public class UserService {

    @Autowired
    private UserMapper userMapper;

    public Boolean checkUserData(String data, Integer type) {
        User user = new User();
        switch (type) {
            case 1 :
                user.setUsername(data);
                break;
            case 2 :
                user.setPhone(data);
                break;
            default:
                throw new LyException(LyExceptionEnum.INVALID_PARAM_ERROR);
        }
        int count = userMapper.selectCount(user);
        return count == 0;
    }

    @Autowired
    private BCryptPasswordEncoder passwordEncoder;

    public void register(User user, String code) {
        // 1. 校验手机验证码

        //2. 密码加密
        String encode = passwordEncoder.encode(user.getPassword());
        user.setPassword(encode);
        //3. 存储数据
        int count = userMapper.insertSelective(user);
        if (count != 1) {
            throw new LyException(LyExceptionEnum.INSERT_OPERATION_FAIL);
        }
    }

    public UserDTO queryUserByNameAndPwd(String username, String password) {
        //根据用户名查询
        User user = new User();
        user.setUsername(username);
        User selectUser = userMapper.selectOne(user);
        if (selectUser == null) {
            throw new LyException(LyExceptionEnum.INVALID_USERNAME_PASSWORD);
        }
        //加密验证密码
        if (!passwordEncoder.matches(password, selectUser.getPassword())) {
            throw new LyException(LyExceptionEnum.INVALID_USERNAME_PASSWORD);
        }
        return BeanHelper.copyProperties(selectUser, UserDTO.class);
    }
}
